var router = require("express").Router();

var User = require("../modules/db/user");
var multer = require("multer");
var md5 = require("md5");

router.get("/editshow", (req, res) => {
  User.findOne((err, user) => {
    res.json({
      error: 0,
      user: user,
    });
  });
});

let uploadpath = "./public/img";
let storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, uploadpath);
  },
  filename(req, file, cb) {
    cb(
      null,
      req.session.user.username + "-" + Date.now() + "-" + file.originalname
    );
  },
});
const upload = multer({
  storage,
});
router.post("/upload", upload.single("myfile"), (req, res) => {
  console.log(req.file);
  var avatarurl = "/img/" + req.file.filename;
  console.log(avatarurl);
  if (req.file) {
    User.findOne({ _id: req.session.user._id }, (err, user) => {
      user.avatar = avatarurl;
      user.save((err) => {
        req.session.user = user;
      });
    });
    res.json({
      error: 0,
      data: "文件上传成功",
    });
  } else {
    res.json({
      error: 1,
      data: "文件上传失败",
    });
  }
});

router.post("/edit", (req, res) => {
  User.findOne((err, user) => {
    user.password = md5(req.body.password);
    user.password2 = md5(req.body.password);
    user.save((err) => {
      req.session.user = user;
      res.json({
        error: 0,
      });
    });
  });
});

module.exports = router;
